﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;

namespace DMSClient
{
    public partial class Conversion : Form
    {
       
        private DataTable dtCurrency;
        private DataTable dtConversion;
        DataSet ds = new DataSet();
        string ambiente;
        int result;
        private string estadoActual = "Guardar";
        
        EndpointAddress address;
        WSHttpBinding Binding = new WSHttpBinding();
        public Conversion()
        {
            InitializeComponent();
            Binding = new WSHttpBinding();
            ambiente = Properties.Settings.Default.CurrentEnv;
            Binding.MaxReceivedMessageSize = 2147483647;
            Binding.MaxBufferPoolSize = 2147483647;
            Binding.ReceiveTimeout = TimeSpan.MaxValue;
            Binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
            Binding.Security.Mode = SecurityMode.None;
            address = new EndpointAddress(Properties.Settings.Default.Server);
            
            this.Text = Properties.Settings.Default.CurrentEnvDes + " - Conversion";

            DMSServices.DMSServicesClient client = new DMSServices.DMSServicesClient(Binding, address);
            string lista = null;
            try
            {
                client.Open();
                lista = client.getCurrency(ambiente);
                client.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, ex.InnerException);
            }
            if (lista == null)
            {
                throw new Exception(Properties.Settings.Default.DistributorsNullListErrorMsg);
            }

            dtCurrency = new DataTable("Currencydt");
            dtCurrency.Columns.Add("idCurrency");
            dtCurrency.Columns.Add("cdCurrency");
            dtCurrency.Columns.Add("dsCurrency");

            DataRow row = dtCurrency.NewRow();
            row["idCurrency"] = "-999";
            row["cdCurrency"] = "Choose...";
            row["dsCurrency"] = "Choose...";
            dtCurrency.Rows.Add(row);


            ds.Tables.Add(dtCurrency);

            System.IO.StringReader xmlSR = new System.IO.StringReader(lista);
            ds.ReadXml(xmlSR, XmlReadMode.ReadSchema);

            xmlSR.Close();


            eceCurrencyFrom.DisplayMember = "dsCurrency";
            eceCurrencyFrom.ValueMember = "idCurrency";
            eceCurrencyFrom.DataSource = ds.Tables[0];
            eceCurrencyFrom.SelectedText = "Choose...";

            eceCurrencyTo.DisplayMember = "dsCurrency";
            eceCurrencyTo.ValueMember = "idCurrency";
            eceCurrencyTo.DataSource = ds.Tables[0];



            eceCurrencyTo.SelectedIndex = 0;
            estadoForm(0);
         
        }

        private void estadoForm(int estado) 
        {

            switch (estado) 
            {
                case 0://Inicial
                    btEdit.Enabled = false;
                    btSave.Enabled = true;

                    eceCurrencyFrom.Enabled = true;
                    eceCurrencyTo.Enabled = true;
                    dtYear.Enabled = true;
                    txValue.ReadOnly = false;
                    txValue.Text = "";
                    eceCurrencyFrom.SelectedIndex = 0;
                    eceCurrencyTo.SelectedIndex = 0;
                    estadoActual = "Guardar";
                break;

                case 1://Consulta realizada
                    btEdit.Enabled = true;
                    btSave.Enabled = false;

                    eceCurrencyFrom.Enabled = false;                   
                    eceCurrencyTo.Enabled = false;
                    dtYear.Enabled = false;
                    txValue.ReadOnly = true;
                    eceCurrencyFrom.Focus();
                break;
                case 2:
                    btEdit.Enabled = false;
                    btSave.Enabled = true;

                    eceCurrencyFrom.Enabled = false;
                    eceCurrencyTo.Enabled = false;
                    dtYear.Enabled = false;
                    txValue.ReadOnly = false;
                    txValue.Focus();

                break;
            
            }
        
        
        }

        private void Conversion_Load(object sender, EventArgs e)
        {
           

            
        }

        public void Filtro(DataTable tab, string filtro)
        {
            
            DataTable dtClone = tab.Clone();
            DataRow row1 = dtClone.NewRow();
            row1["idCurrency"] = "-999";
            row1["cdCurrency"] = "Choose...";
            row1["dsCurrency"] = "Choose...";
            dtClone.Rows.Add(row1);
           
            foreach (DataRow row in tab.Rows)
            {

                if (!row[0].ToString().Equals(filtro) && !row[0].ToString().Equals("-999"))
                {
                    DataRow fila = dtClone.NewRow(); ;
                    fila["idCurrency"] = row[0].ToString();
                    fila["cdCurrency"] = row[1].ToString();
                    fila["dsCurrency"] = row[2].ToString();

                    dtClone.Rows.Add(fila);
                }

            }
            eceCurrencyTo.DataSource = dtClone;
        }

        private void eceCurrencyTo_ValueChanged(object sender, EventArgs e)
        {         
          
            ConsultarConversion();
            Filtro(ds.Tables[0], eceCurrencyFrom.Value.ToString());
            
        }

        private void ultraButton1_Click(object sender, EventArgs e)
        {
            GetConversionWorker.RunWorkerAsync();
            estadoLoader(true);            
            }
            
        

        private bool validaDatos() 
        {
            if (eceCurrencyFrom.Value.ToString().Equals("-999")) 
            {
                MessageBox.Show("Please choose CurrencyTo");
                return false;
            }

            if (eceCurrencyTo.Value.ToString().Equals("-999"))
            {
                MessageBox.Show("Please choose CurrencyFrom");
                return false;
            }

            if (txValue.Text.ToString().Equals("")) 
            {
                MessageBox.Show("Please enter Value");
                return false;
            }
            return true;
        }

              

        private void eceCurrencyFrom_ValueChanged(object sender, EventArgs e)
        {
            
            ConsultarConversion();
            
            
        }

        private void dtYear_ValueChanged(object sender, EventArgs e)
        {
           
            ConsultarConversion();
        }

        private void ConsultarConversion()
        {
           try
            {
                if (ds.Tables.Count > 1) 
                {
                    ds.Tables.Remove("Conversiondt");
                }
                int idCurrencyTo = int.Parse(eceCurrencyTo.Value.ToString());
                int idCurrencyFrom = int.Parse(eceCurrencyFrom.Value.ToString());
                if (idCurrencyFrom != -999 && idCurrencyTo != -999)
                {
                    DateTime fecha = DateTime.Parse(dtYear.Value.ToString());
                    short year = short.Parse(fecha.Year.ToString());

                    DMSServices.DMSServicesClient client;
                    client = new DMSServices.DMSServicesClient(Binding, address);
                    string itemConver = null;
                    try
                    {
                        client.Open();
                        itemConver = client.getConversion(idCurrencyTo, idCurrencyFrom, year, ambiente);
                        client.Close();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, ex.InnerException);
                    }
                    if (itemConver == null)
                    {
                        throw new Exception(Properties.Settings.Default.DistributorsNullListErrorMsg);
                    }

                    dtConversion = new DataTable("Conversiondt");
                    dtConversion.Columns.Add("idCurrencyTo");
                    dtConversion.Columns.Add("idCurrencyFrom");
                    dtConversion.Columns.Add("nrYear");
                    dtConversion.Columns.Add("vlConversion");
                    dtConversion.Columns.Add("flRemoteDelete");
                    dtConversion.Columns.Add("dtLastModified");
                    ds.Tables.Add(dtConversion);

                    System.IO.StringReader xmlSR = new System.IO.StringReader(itemConver);
                    ds.ReadXml(xmlSR, XmlReadMode.ReadSchema);

                    xmlSR.Close();
                    txValue.Text = "";
                    if (dtConversion.Rows.Count != 0 && dtConversion != null)
                    {
                        double vl = double.Parse(dtConversion.Rows[0]["vlConversion"].ToString().Replace('.',','));
                        txValue.Text = vl.ToString();
                        loader.Visible = false;
                        estadoForm(1);
                    }
                }

            }
            catch (NullReferenceException exc) { }
            catch (FormatException exc1) { }
        }

        private void GetConversionWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            result = 0;
            Dtl.Conversion conversion = new Dtl.Conversion();
            if (validaDatos())
            {
                conversion.idCurrencyTo = int.Parse(eceCurrencyTo.Value.ToString());
                conversion.idCurrencyFrom = int.Parse(eceCurrencyFrom.Value.ToString());
                DateTime fecha = DateTime.Parse(dtYear.Value.ToString());
                int anio = fecha.Year;
                conversion.nrYear = short.Parse(anio.ToString());
                conversion.vlConversion = decimal.Parse(txValue.Text.ToString());
                
                DMSServices.DMSServicesClient client;
                client = new DMSServices.DMSServicesClient(Binding, address);


                try
                {
                    client.Open();
                    if (estadoActual.Equals("Guardar"))
                    {
                        result = client.setConversion(conversion, ambiente);
                    }
                    else
                    {

                        result = client.editConversion(conversion, ambiente);
                    }
                    client.Close(); 
                    
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message, ex.InnerException);
                }
                if (result == null)
                {
                    throw new Exception("Error");
                }

               
            }
        }

        private void GetConversionWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    estadoLoader(false);
                    if (result == -1)
                    {
                        MessageBox.Show("Successfully saved record!", "Conversion");
                        estadoForm(0);
                    }
                    else
                        MessageBox.Show("Error saving the record, please try again!", "Conversion");
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                loader.Visible = false;
                estadoLoader(true);
            
            }
             
        }

        private void ultraTextEditor1_ValueChanged(object sender, EventArgs e)
        {

        }

        private void btCancel_Click(object sender, EventArgs e)
        {
            estadoForm(0);
        }

        private void btEdit_Click(object sender, EventArgs e)
        {
            estadoActual = "Modificar";
            estadoForm(2);
        }

        public void estadoLoader(bool estado)
        {
            loader.Visible = estado;
        }

        private void Conversion_Shown(object sender, EventArgs e)
        {
            loader.Left = (this.Width - loader.Width) / 2;
            loader.Top = ((this.Height - loader.Height) / 2) - loader.Height;
        }

        private void Conversion_Resize(object sender, EventArgs e)
        {
            loader.Left = (this.Width - loader.Width) / 2;
            loader.Top = ((this.Height - loader.Height) / 2) - loader.Height;
        }

    }
}
